//
//  catchAllException.hpp
//  learnC++
//
//  Created by liuzhibing on 2018/6/25.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#ifndef catchAllException_hpp
#define catchAllException_hpp

#include <stdio.h>
#include <iostream>

using namespace std;

//异常类
class ArrayException
{
private:
    std::string m_error;
    
public:
    ArrayException(std::string error)
    : m_error(error)
    {
    }
    
    const char* getError() { return m_error.c_str(); }
};

//派生系统异常类
class ArrayException2: public std::exception
{
private:
    std::string m_error;
    
public:
    ArrayException2(std::string error)
    : m_error(error)
    {
    }
    
    // return the std::string as a const C-style string
    //    const char* what() const { return m_error.c_str(); } // pre-C++11 version
    //这意味着函数承诺不会抛出异常本身
    const char* what() const noexcept { return m_error.c_str(); } // C++11 version
};

class CatchAllException {
private:
    int m_value;
    
public:
    CatchAllException(){
        
        try {
//            throwException();
            //标准库出错后抛出的异常
            
            std::string s;
            s.resize(-1);
            
            //自定义exception.what()消息
            throw std::runtime_error("Bad things happend");
            
        }
        catch (double x) {
            cout << "catch Exception Double~";
            
            //重新抛出与刚刚捕获的异常相同的异常的方法
//            throw;
            
            //有时候返回数字调用者不知道是什么错误,可以重新抛出异常
            throw "q is large";
            
            
        }
        catch (ArrayException &ex){
            std::cerr << "An array exception occurred (" << ex.getError() << ")\n";
        }
        catch (std::bad_alloc &exception)
        {
            std::cerr << "You ran out of memory!" << '\n';
        }
        catch (std::exception &exception) {
            cout << "Standard exception:" << exception.what();
        }
        catch (...){
            //...表示捕获任何异常
            cout << "catch Exception undefine~";
        }
        
    }
    
    
    void throwException(){
        
        throw ArrayException("Invalid index");
        
    }
    
};


/*
 int doSomething() throw(); // does not throw exceptions
 int doSomething() throw(double); // may throw a double
 int doSomething() throw(...); // may throw anything
 */

#endif /* catchAllException_hpp */
